import { useState, useRef } from "react"
import * as mockjs from "mockjs"
import { AnimatePresence, motion } from "motion/react"

export default function ReactAnimationPage() {
  const isFirstRender = useRef(true);
  const [list, setList] = useState(() => {
    return new Array(10).fill(0).map(_ => {
      return {
        id: Math.random(),
        content: mockjs.Random.cword(1, 10)
      }
    })
  })
  function addItem() {
    isFirstRender.current = false
    const newItem = {
      id: Math.random(),
      content: mockjs.Random.cword(1, 10)
    }
    setList([...list, newItem])
  }
  function removeItem(id: number) {
    setList(list.filter(item => item.id !== id))
  }
  return (
    <div className="p-4 max-w-md mx-auto">
      <button
        onClick={addItem}
        className="px-4 py-2 bg-blue-500 text-white rounded-lg mb-4"
      >
        添加项目
      </button>
      <ul className="space-y-2">
        <AnimatePresence>
          {list.map((item) => (
            <motion.li
              key={item.id}
              initial={isFirstRender.current ? false : { opacity: 0, y: -20 }}
              // initial={{ opacity: 0, y: -20 }} // 初始状态（透明且向上偏移）
              animate={{ opacity: 1, y: 0 }} // 动画到最终状态
              exit={{ opacity: 0, y: -20 }} // 退出时动画
              transition={{ duration: 0.3 }} // 动画时间
              className="p-2 bg-gray-200 rounded-lg flex justify-between items-center"
            >
              {item.content}
              <button
                onClick={() => removeItem(item.id)}
                className="text-red-500 text-sm"
              >
                删除
              </button>
            </motion.li>
          ))}
        </AnimatePresence>
      </ul>
    </div>
  )
}